clear
discard
set more off

adopath ++ "./ado/"
adopath ++ "../tools/"
adopath ++ "../ssc/"

******************
*** Parameters ***
******************

local file_name "./input/individual_dataset.csv" // Data file
local output_folder "./output/individual" // Output directory
local K = 4 // Number of lags to include when calculating local projections
local L = 16 // Number of IRF coefficients to estimate
local alpha = 0.05 // Significance level

*************************************
*** Import data and set data type ***
*************************************

import delimited using `file_name', case(preserve)

gen qtr = quarterly(DATE,"YQ")
format qtr %tq
xtset ID qtr // Set to panel data

**************************
*** Generate variables ***
**************************

* Forecast errors
gen Efor_Step2 = Realiz1 - SPFfor_Step2

* Generate winsorized variable
winsor2 Efor_Step2, suffix(_w) cuts(5 95)

***********************************
*** Calculate local projections ***
***********************************

* Main regression
estimate_IRF_LP Efor_Step2, l(`L') k(`K') alpha(`alpha') ///
	method("fe") fe_var("ID") cluster_var("ID") cluster_var_two_way("qtr") 
matrix IRF = e(s)

* Winsorized regression
estimate_IRF_LP Efor_Step2_w, l(`L') k(`K') alpha(`alpha') ///
	method("fe") fe_var("ID") cluster_var("ID") cluster_var_two_way("qtr") 
matrix IRF_w = e(s)

* Estimate a simple AR(4) for forecast errors
quietly reghdfe Efor_Step2 l1.Efor_Step2 l2.Efor_Step2 l3.Efor_Step2 l4.Efor_Step2, ///
	absorb(ID) vce(cluster ID qtr)
matrix AR_coefs = e(b)
matrix AR_coefs_cov = e(V)

******************
*** Get graphs ***
******************

* Clean up
shell rm -r `output_folder'
shell mkdir -p ./output
shell mkdir `output_folder'

* Get plots
plot_IRF "IRF" `output_folder' "IRF"

* Save estimated IRFs
mat2txt, matrix(IRF) saving(`output_folder'/IRF_LP_1Q_ahead.txt)
mat2txt, matrix(IRF_w) saving(`output_folder'/IRF_LP_1Q_ahead_winsorized.txt)
mat2txt, matrix(AR_coefs) saving(`output_folder'/AR_coefs_1Q_ahead.txt)
mat2txt, matrix(AR_coefs_cov) saving(`output_folder'/AR_coefs_cov_1Q_ahead.txt)

* Get summary statistics
summary_stats_forecasts Efor_Step2 Realiz1, k(`K')
matrix stats_Step2 = e(s)
mat2txt, matrix(stats_Step2) saving(`output_folder'/stats_1Q_ahead.txt)
